﻿using Controllers.DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Middleware;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using System.Linq;
using Model;
using System.Reflection.Metadata.Ecma335;


namespace Controllers
{
    [Authorize]//该api需要授权
    [ApiController]//这里是api
    [Route("[controller]")]//api路由规则
    public class UsersController:ControllerBase
    {
        private readonly DBHelper _dB;
        private readonly IMapper _mapper;
        public UsersController(DBHelper db,IMapper mapper)
        { 
            _dB= db;
            _mapper= mapper;
        }
        /// <summary>
        /// 访问：http://ip:{port}/Users/all
        /// 按name查询 
        /// 访问方法get
        /// </summary>
        /// <param name="name">查询参数</param>
        /// <returns></returns>
        [HttpGet("all")]
        public  IList<UsersDto> GetUsers(string name)
        {
            string sql = "select * from Users where username like '%"+name+"%'";
            return _dB.GetList<Users>(sql).Select(m=> _mapper.Map<UsersDto>(m)
           ).ToList();
        }
        /// <summary>
        ///  访问：http://ip:{port}/Users
        ///  访问方法post
        ///  功能：添加用户
        /// </summary>
        /// <param name="user">由body传入</param>
        [HttpPost]
        public void AddUser(UsersDto user)
        {
            user.PrimaryKey = Guid.NewGuid().ToString("N");
            user.Password = user.Password.EncryPassword(user.PrimaryKey);
            
            _dB.ExcuteEntity(_mapper.Map<Users>(user), SqlOperate.Insert,this.HttpContext);
        }
        /// <summary>
        ///  访问：http://ip:{port}/Users
        ///  访问方法put
        ///  功能：修改用户
        /// </summary>
        /// <param name="user">由body传入</param>
        [HttpPut]
        public void UpdateUser(UsersDto user)
        {
            user.PrimaryKey = Guid.NewGuid().ToString("N");
            user.Password = user.Password.EncryPassword(user.PrimaryKey);
            _dB.ExcuteEntity(_mapper.Map<Users>(user), SqlOperate.Update, this.HttpContext);
        }
        /// <summary>
        ///  访问：http://ip:{port}/Users
        ///  访问方法delete
        ///  功能：删除用户
        /// </summary>
        /// <param name="user">由body传入</param>
        [HttpDelete]
        public void DeleteUser(UsersDto user)
        {
            _dB.ExcuteEntity(_mapper.Map<Users>(user), SqlOperate.Delete, this.HttpContext);
        }
        
        
    }
}
